package com.baize.filedowndemo.workmanager

import android.annotation.SuppressLint
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.util.Log
import androidx.core.app.NotificationCompat
import androidx.work.*
import androidx.work.impl.utils.futures.SettableFuture
import com.baize.filedowndemo.MainActivity
import com.baize.filedowndemo.R
import com.baize.filedowndemo.conversationFile.ProgressInterceptor
import com.google.common.util.concurrent.ListenableFuture
import okhttp3.*
import okhttp3.logging.HttpLoggingInterceptor
import java.util.concurrent.TimeUnit

class UploadWorker(val context: Context, workerParams: WorkerParameters) :
  Worker(context, workerParams) {

  @SuppressLint("RestrictedApi")
  override fun getForegroundInfoAsync(): ListenableFuture<ForegroundInfo> {
    val notification = NotificationCompat.Builder(context, "some-channel-id").setContentIntent(
        PendingIntent.getActivity(
          context,
          0,
          Intent(context, MainActivity::class.java),
          PendingIntent.FLAG_UPDATE_CURRENT
        )
      )
      .setSmallIcon(R.drawable.ic_launcher_foreground)
      .setOngoing(true).setAutoCancel(true)
      .setOnlyAlertOnce(true).setPriority(NotificationCompat.PRIORITY_MIN)
      .setContentTitle("FileDownDemoTitle").setLocalOnly(true)
      .setVisibility(NotificationCompat.VISIBILITY_SECRET).setContentText("Updating widget").build()
    val future : SettableFuture<ForegroundInfo> = SettableFuture.create()
    future.set(ForegroundInfo(1337, notification))
    return future

  }

  override fun doWork(): Result {

    // Do the work here--in this case, upload the images.
    Log.i("baize_","当前线程：${Thread.currentThread().name}")
    val downloadUrl = inputData.getString("IMAGE_URI") ?: return Result.failure()

    val okHttpClient =
      OkHttpClient.Builder().readTimeout(30, TimeUnit.SECONDS).writeTimeout(30, TimeUnit.SECONDS)
        .addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
        .addInterceptor(ProgressInterceptor()).build()

    val request = Request.Builder().url(downloadUrl).build()

    try {
      val response = okHttpClient.newCall(request).execute()
      if (response.isSuccessful) {
        Log.i("baize_", "onFailure: ${response}")
        ProgressInterceptor.removeListener(downloadUrl)
        val output: Data = workDataOf("KEY_RESULT" to "failure!")
        return Result.failure(output)
      } else {
        Log.i("baize_", "onResponse: ${response.code} ${response.body}")
        ProgressInterceptor.removeListener(downloadUrl)
        val output: Data = workDataOf("KEY_RESULT" to response.code)
        return Result.success(output)
      }
    } catch (e: Exception) {
      val output: Data = workDataOf("KEY_RESULT" to e.message)
      return Result.failure(output)
    }
    //    okHttpClient.newCall(request).enqueue(object : Callback {
    //      override fun onFailure(call: Call, e: IOException) {
    //      }
    //
    //      override fun onResponse(call: Call, response: Response) {
    //      }
    //    })


//     Indicate whether the work finished successfully with the Result
  }
}